const moment = require('moment')
const Coupon = require('../../model/Coupon')
const CollectedCoupon = require('../../model/CollectedCoupon')
const request = require('request')

const wxPublicAccessToken = require('../../util/businessUtil/wxPublicAccessToken')

module.exports = {



    changeCoupon: async(req, res, next) => {
        try {
            let add = true
            let change = false
            if (add) {
                wxPublicAccessToken.getAccessToken(function(token) {
                    let wxurl = "https://api.weixin.qq.com/card/create?access_token=" + token
                    let postdata = {
                        "card": {
                            "card_type": "GENERAL_COUPON",
                            "general_coupon": {
                                "base_info": {
                                    "logo_url": "http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFNjakmxibMLGWpXrEXB33367o7zHN0CwngnQY7zb7g/0",
                                    "code_type": "CODE_TYPE_QRCODE",
                                    "brand_name": "商户名测试",
                                    "title": "卡券名",
                                    "color": "Color090",
                                    "notice": "请出示二维码",
                                    "description": "使用说明",
                                    "sku": {
                                        "quantity": 1000, //数量上限
                                    },
                                    "date_info": { //使用日期
                                        // "type": "DATE_TYPE_FIX_TIME_RANGE", //日期区间
                                        "type": "DATE_TYPE_FIX_TERM", //领用后时长
                                        // "begin_timestamp": 1597577600,
                                        // "end_timestamp": 1697577600,
                                        "fixed_term": 15,
                                        "fixed_begin_term": 0,
                                        "end_timestamp": 1697577600
                                    },
                                },
                                "advanced_info": {},
                                "default_detail": "优惠券测试"
                            }
                        }
                    }
                    request({
                        url: wxurl,
                        method: "POST",
                        timeout: 10000,
                        body: postdata,
                        followRedirect: true,
                        json: true,
                        maxRedirects: 10
                    }, function(error, response, body) {
                        console.log(error, body, 'dd')
                            // let newMemberCard = new MemberCard({
                            //     cardId: body.card_id
                            // })
                            // newMemberCard.save(function() {
                        if (!error) {
                            res.ok('创建优惠券成功')
                        }
                        // })
                    })
                })
            } else if (change) {
                getToken(function(token) {
                    console.log(token)
                })
            }





            // if (req.body.id) {
            //     let coupon = await Coupon.findById(req.body.id).exec()
            //     coupon.store = req.body.store,
            //         coupon.title = req.body.title,
            //         coupon.validType = req.body.validType,
            //         coupon.discountType = req.body.discountType,
            //         coupon.discount = req.body.discount,
            //         coupon.updatedAt = new Date(),
            //         coupon.description = req.body.description,
            //         coupon.pickExpireDate = req.body.pickExpireDate,
            //         coupon.pickStartDate = req.body.pickStartDate,
            //         coupon.useExpireDate = req.body.useExpireDate,
            //         coupon.useStartDate = req.body.useStartDate,
            //         coupon.useExpireType = req.body.useExpireType,
            //         coupon.useExpireDay = req.body.useExpireDay,
            //         coupon.totalCount = req.body.totalCount,
            //         coupon.currentCount = req.body.totalCount,
            //         coupon.limit = req.body.limit || 1,
            //         coupon.appliedProduct = req.body.appliedProduct,
            //         coupon.appliedProductCategory = req.body.appliedProductCategory
            //     await coupon.save()
            //     res.ok('创建成功', coupon)
            // } else if (!req.body.id) {
            //     let newCoupon = new Coupon({
            //         store: req.body.store,
            //         title: req.body.title,
            //         validType: req.body.validType,
            //         discountType: req.body.discountType,
            //         discount: req.body.discount,
            //         updatedAt: new Date(),
            //         description: req.body.description,
            //         pickExpireDate: req.body.pickExpireDate,
            //         pickStartDate: req.body.pickStartDate,
            //         useExpireDate: req.body.useExpireDate,
            //         useStartDate: req.body.useStartDate,
            //         useExpireType: req.body.useExpireType,
            //         useExpireDay: req.body.useExpireDay,
            //         totalCount: req.body.totalCount,
            //         currentCount: req.body.totalCount,
            //         limit: req.body.limit || 1,
            //         appliedProduct: req.body.appliedProduct,
            //         appliedProductCategory: req.body.appliedProductCategory,
            //         status: 0,
            //         isDelete: 0,
            //     })
            //     await newCoupon.save()
            //     res.ok('创建成功', newCoupon)
            // }
        } catch (e) {
            next(e)
        }
    },

    deleteCoupon: async(req, res, next) => {
        try {
            let coupon = await Coupon.findOne({ _id: req.body.id }).exec()
            coupon.isDelete = 1
            await coupon.save()
            res.ok('删除成功', coupon)
        } catch (e) {
            next(e)
        }
    },

    getCouponCollectedList: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if (req.body.status) {
                option.status = req.body.status
            }
            if (req.body.coupon) {
                option.coupon = req.body.coupon
            }
            let count = await CollectedCoupon.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await CollectedCoupon.find(option).skip((page - 1) * pageSize).limit(pageSize).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },

    couponOnshelf: async(req, res, next) => {
        try {
            let coupon = await Coupon.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            coupon.status = 1
            await coupon.save()
            res.ok('上线成功', coupon)
        } catch (e) {
            next(e)
        }
    },

    couponOffShelf: async(req, res, next) => {
        try {
            let coupon = await Coupon.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            coupon.status = 0
            await coupon.save()
            res.ok('下线成功', coupon)
        } catch (e) {
            next(e)
        }
    },

    getCouponList: async(req, res, next) => {
        try {
            wxPublicAccessToken.getAccessToken(function(token) {
                let wxurl = "https://api.weixin.qq.com/card/batchget?access_token=" + token
                let postdata = {
                    "offset": (req.body.page - 1) * req.body.pageSize,
                    "count": req.body.pageSize,
                    "status_list": [] // “CARD_STATUS_NOT_VERIFY”, 待审核 ； “CARD_STATUS_VERIFY_FAIL”, 审核失败； “CARD_STATUS_VERIFY_OK”， 通过审核； “CARD_STATUS_DELETE”， 卡券被商户删除； “CARD_STATUS_DISPATCH”， 在公众平台投放过的卡券
                }
                request({
                    url: wxurl,
                    method: "POST",
                    timeout: 10000,
                    body: postdata,
                    followRedirect: true,
                    json: true,
                    maxRedirects: 10
                }, function(error, response, body) {
                    let result = {}
                    result.total = body.total_num
                    result.currentPage = req.body.page
                    result.data = []
                    result.pageSize = req.body.pageSize
                    let times = 0
                    if (body.card_id_list.length == 0) {
                        return res.ok('查询失败')
                    }
                    body.card_id_list.map(e => {
                            let postonedata = {
                                "card_id": e
                            }
                            let wxgetonecardurl = "https://api.weixin.qq.com/card/get?access_token=" + token
                            request({
                                url: wxgetonecardurl,
                                method: "POST",
                                timeout: 10000,
                                body: postonedata,
                                followRedirect: true,
                                json: true,
                                maxRedirects: 10
                            }, function(error, response, bodys) {
                                result.data.push(bodys.card)
                                times += 1
                                if (times == body.card_id_list.length) {
                                    res.ok('优惠券查询成功', result)
                                }
                                // if (!error) {
                                //     res.ok('优惠券查询成功', body)
                                // }
                            })
                        })
                        // if (!error) {
                        //     console.log(result)
                        //     res.ok('优惠券查询成功', result)
                        // }
                })
            })








            // let option = {}
            // if (req.body.name) {
            //     option.title = new RegExp(req.body.name, 'i')
            // }
            // if (req.body.status) {
            //     option.status = req.body.status
            // }
            // let count = await Coupon.countDocuments(option).exec()
            // let page = req.body.page || 1
            // let pageSize = req.body.pageSize || count
            // let data = await Coupon.find(option).skip((page - 1) * pageSize).limit(pageSize).exec()
            // let result = {}
            // result.total = count
            // result.currentPage = page
            // result.data = data
            // result.pageSize = pageSize
            // res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },


    getOneCoupon: async(req, res, next) => {
        try {
            wxPublicAccessToken.getAccessToken(function(token) {
                let wxurl = "https://api.weixin.qq.com/card/get?access_token=" + token
                let postdata = {
                    "card_id": req.body.card_id
                }
                console.log(postdata)
                request({
                    url: wxurl,
                    method: "POST",
                    timeout: 10000,
                    body: postdata,
                    followRedirect: true,
                    json: true,
                    maxRedirects: 10
                }, function(error, response, body) {
                    console.log(error, body, 'dd')
                    if (!error) {
                        res.ok('优惠券查询成功', body)
                    }
                })
            })
        } catch (e) {
            next(e)
        }
    },

};